package top.bingoz.wanandroid


import android.annotation.SuppressLint
import android.content.Context
import android.view.View
import android.widget.TextView
import android.widget.Toast
import com.google.gson.Gson
import top.bingoz.wanandroid.common.Constants
import top.bingoz.wanandroid.common.utils.Timber

/**
 * Log
 */
fun logd(data: Any?, message: String? = null) {
    log(data, message = message)
}

fun loge(data: Any?, message: String? = null) {
    log(data, error = true, message = message)
}

private fun log(data: Any?, error: Boolean = false, message: String? = null) {
    data ?: return
    if (data is String) {
        when (error) {
            false -> Timber.d(data)
            else -> Timber.e(data)
        }
    } else if (data is Throwable) {

        when (error) {
            false -> Timber.d(data, message)
            else -> Timber.e(data, message)
        }

    } else {
        when (error) {
            false -> Timber.d(Gson().toJson(data))
            else -> Timber.e(Gson().toJson(data))
        }
    }

}

fun Context.toast(content: String?) {

    Constants.App.TOAST?.apply {
        cancel()
        showToast(content)
    } ?: run {
        showToast(content)
    }
}

@SuppressLint("ShowToast")
private fun Context.showToast(content: String?) {
    content ?: return

    Toast.makeText(applicationContext, content, Toast.LENGTH_SHORT).apply {
        view = view()
        view.findViewById<TextView>(R.id.toastMessage).setText(content)
        Constants.App.TOAST = this
    }.show()
}

private fun Context.view(): View {

    return Constants.App.VIEW
            ?: View.inflate(this.applicationContext, R.layout.toast_layout, null).apply {
                Constants.App.VIEW = this
            }
}